package com.allen.study.domain.utils.security;

import com.allen.study.test_common.constant.CacheConstants;
import com.allen.study.test_common.utils.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName: CustomAuthenticationSuccessHandler
 * @Author: AllenSun
 * @Date: 2025/3/18 00:34
 */
@Component
@Slf4j
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 认证成功后的自定义逻辑，例如重定向到特定页面
        // response.sendRedirect("/success");
        String username = request.getParameter("username");
        log.info("认证成功：{}",username);
        String retryCountKey = CacheConstants.PWD_ERR_CNT_KEY + username;
        // 如果密码正确匹配，则删除清空密码登录失败的次数缓存
        if (redisUtils.hasKey(retryCountKey)) {
            redisUtils.del(retryCountKey);
        }
    }
}
